package com.cn.项目.飞机预约管理系统.chat;

import javax.swing.*;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

public class ChatPanelSocket extends ChatPanel implements Runnable {

    //客户端Socket
    protected Socket socket;
    //读数据
    protected DataInputStream input;
    //写数据
    protected DataOutputStream output;

    //线程对象，用于接收对方发送的字符串
    protected  Thread thread;
    public ChatPanelSocket(){
        super();
    }

    protected void sendButton(){
        try {
            //发送聊天内容，对方在run方法中接收
            output.writeUTF(nickname+"说："+southField.getText());
            //在文本中显示
            jTextArea.append("我说："+southField.getText()+"\n");
            //清空南边输入发送内容的文本框
            southField.setText("");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //覆盖本类方法实现“离线”按钮执行的动作
    protected void exitButton(){
        try {
            output.writeUTF("bye");
            sendButton.setEnabled(false);
            exitButton.setEnabled(false);
            jTextArea.append("连接断开");
            socketClosing();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //接收发来的字符串
    @Override
    public void run() {
        System.out.println("线程启动");
        String instr="";
        while (true){
            try {
                instr =  input.readUTF();
                if (instr.equals("bye")){
                    sendButton.setEnabled(false);
                    exitButton.setEnabled(false);
                    jTextArea.append("连接断开！！");
                    socketClosing();
                    break;
                }else {
                    jTextArea.append(instr+"\n");
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("有异常，连接中断");
                break;
            }
        }
        System.out.println("线程结束");

    }
   //关闭所有连接
    private void socketClosing() {
        try {
            input.close();
            output.close();
            socket.close();
        } catch (Exception e) {
            System.out.println("关闭Socket和流时，发生异常！");
        }
    }

    public static void main(String[] args) {
        JFrame app = new JFrame("具有聊天的聊天界面");
        app.getContentPane().add(new ChatPanelSocket());
        app.setSize(400,300 );
        app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        app.setVisible(true);
    }

}
